<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #file="{ model, field }">
        <BasicUpload
          :max-size="20"
          :max-number="5"
          @change="handleChange"
          @delete="deleteAttach"
          @preview-delete="deleteAttachPreview"
          :accept="['.doc,', 'docx', 'application/msword', 'image/*']"
          v-model:value="model[field]"
          :api="uploadOpmsFile"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './opmsDistressRelief.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    createOpmsDistressRelief,
    updateOpmsDistressRelief,
    uploadOpmsFile,
  } from '/@/api/distress/opmsDistressRelief';
  import BasicUpload from '/@/components/Upload/src/BasicUpload.vue';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const { createMessage } = useMessage();

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  // const attachList = ref();
  const fileUrls = ref<string[]>([]);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    fileUrls.value = [];
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    updateSchema([
      { field: 'applicant', label: '申请人', componentProps: { disabled: unref(isUpdate) } },
      { field: 'type', label: '救助类型', componentProps: { disabled: unref(isUpdate) } },
      { field: 'level', label: '救助级别', componentProps: { disabled: !unref(isUpdate) } },
      { field: 'file', label: '申请材料', componentProps: { disabled: unref(isUpdate) } },
      { field: 'money', label: '救助金额', componentProps: { disabled: unref(isUpdate) } },
      { field: 'reason', label: '申请原因', componentProps: { disabled: unref(isUpdate) } },
      { field: 'status', label: '申请状态', componentProps: { disabled: !unref(isUpdate) } },
    ]);
    if (unref(isUpdate)) {
      updateSchema([
        { field: 'level', label: '救助级别', component: 'Select', show: true, required: true },
        {
          field: 'status',
          label: '申请状态',
          component: 'Select',
          show: true,
          required: true,
        },
      ]);
      if (data.record.files) {
        data.record.files = data.record.files.map((i) => i.attachFilePath);
      }
      console.log('文件文件', data.record);
      setFieldsValue({
        ...data.record,
      });
    }
  });
  const getTitle = computed(() => (!unref(isUpdate) ? '新增困难救助表' : '编辑困难救助表'));

  //文件列表内容改变触发事件
  function handleChange(fileList) {
    // const files = fileList.map((file:string) => ({
    //   attachFileName: file.substring(file.lastIndexOf('/')),
    //   attachFilePath: file,
    // }));
    console.log('上传文件---》', fileList);
    // attachList.value.push(...files);
  }

  //在上传列表中删除文件的事件
  function deleteAttach(record) {}

  //在预览列表中删除文件的事件
  function deleteAttachPreview(url: string) {}

  async function handleSubmit() {
    try {
      const values = await validate();
      values.files = values.files.map((f) => ({
        attachFileName: f.substring(f.lastIndexOf('/') + 1),
        attachFilePath: f,
      }));
      //处理日期格式 如果后台日期对象为LocalDate 转换后的为 YYYY-MM-DD ，但是前端的日期选择器是 YYYY-MM-DD hh:mm:ss,需要转换一下
      setModalProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        await updateOpmsDistressRelief(values);
        createMessage.success('更新成功');
      } else {
        await createOpmsDistressRelief(values);
        createMessage.success('创建成功');
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<script lang="ts">
  export default { name: 'OpmsDistressReliefModal' };
</script>
